package com.easyadmin.pro.modules.sys.service.impl;

import com.easyadmin.pro.common.constants.StatusConstants;
import com.easyadmin.pro.common.enums.HttpCodeEnum;
import com.easyadmin.pro.common.exception.EasyAdminProBaseException;
import com.easyadmin.pro.modules.sys.entity.UserEntity;
import com.easyadmin.pro.modules.sys.mapper.UserMapper;
import com.easyadmin.pro.modules.sys.vo.UserVo;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * packageName com.easyadmin.pro.modules.sys.service.impl
 *
 * @author 骑着蚂蚁去上天
 * @version JDK 17
 * @className UserDetailServiceImpl
 * @date 2024/4/1
 * @description 访问登录实现接口
 */
@Component
public class UserDetailServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserEntity userEntity = userMapper.selectOneByQuery(new QueryWrapper()
                .eq(UserEntity::getUserName, username));
        if (Objects.isNull(userEntity)) {
            throw new EasyAdminProBaseException(HttpCodeEnum.LOGIN_ERROR);
        }
        if (!Objects.equals(StatusConstants.STATUS_1, userEntity.getStatus())) {
            throw new EasyAdminProBaseException(HttpCodeEnum.USER_STATUS_0);
        }
        return new UserVo(userEntity, null);
    }
}